﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccessLayer.Properties;
using System.Transactions;
using IMModel.Domain;

namespace DataAccessLayer.Admin.Copy.IndexMarkStruct
{
    public class CategoryCopy : ICopy
    {
        /// <summary>
        /// Если данная категория уже существует, то не создает новой категории, а возвращает IDCategoryTerm существующей
        /// </summary>
        /// <param name="IDCopiedObject"></param>
        /// <param name="IDParentObject"></param>
        /// <param name="fromIDTerm"></param>
        /// <param name="toIDTerm"></param>
        /// <returns></returns>
        public int Copy(int IDCopiedObject, int? IDParentObject, int fromIDTerm, int toIDTerm)
        {
            using (IMModel.Domain.IMDataDataContext db = new IMModel.Domain.IMDataDataContext(Settings.Default.IndexMarkConnectionString))
            {
                CategoryTerm old = db.CategoryTerms.Single(s => s.IDCategoryTerm == IDCopiedObject);

                CategoryTerm tmp = db.CategoryTerms.FirstOrDefault(s => s.IDCategory == old.IDCategory && s.IDTerm == toIDTerm);
                if (tmp != null) return tmp.IDCategoryTerm;

                CategoryTerm _new = new CategoryTerm
                {
                    IDCategory = old.IDCategory,
                    IDTerm = toIDTerm,
                    Weight = old.Weight
                };

                db.CategoryTerms.InsertOnSubmit(_new);
                db.SubmitChanges();

                return _new.IDCategoryTerm;
            }
        }
    }
}
